package com.example.test7;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
    private IntentFilter intentFilter;
    private PowerConnectionReceiver powerConnectionReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intentFilter = new IntentFilter();

//        创建广播对象
        powerConnectionReceiver = new PowerConnectionReceiver();
//        添加电池改变的活动
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(powerConnectionReceiver,intentFilter);
    }

    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(powerConnectionReceiver);
    }

//    检测电量的广播
    private class PowerConnectionReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {

//        电池的状态
            int status = intent.getExtras().getInt(BatteryManager.EXTRA_STATUS);
            if (BatteryManager.BATTERY_STATUS_CHARGING == status) {
//            充电中
                Log.d("充电状态", "正在充电中。。。。");
            } else if (BatteryManager.BATTERY_STATUS_CHARGING == status) {
//            未充电
                Log.d("充电状态", "未在充电。");
            }

//        获取当前的电量，总电量
            int level = intent.getExtras().getInt(BatteryManager.EXTRA_LEVEL, 0);//当前电量；
            int total = intent.getExtras().getInt(BatteryManager.EXTRA_SCALE, 100);//总电量
            float batteryPct = level / (float) total;
            if (batteryPct < 0.5) {
                Log.d("电量", "电量低，请充电");
            } else {
                Log.d("电量", "电量尚可");
            }
        }
}
}